
layui.use(function () {
    var $ = layui.$;
    var layer = layui.layer;
    var util = layui.util;
    var form = layui.form;
    var table = layui.table;

    var selectedRows = [];
    var storageslis = {};
    var storageselect = {};
    var storageNums = {};

    var token = localStorage.getItem("token");

    //显示表格
    function Getprocurement(pageNum) {
        var dto = {
            Token: token,
            pindex: 1,
            psize: 100,
            ProcurementCode: $("#procurementCode").val(),
            ProductsCode: $("#productsCode").val(),
            ProductsName: $("#productsName").val(),
            ProcureState: $("#procureState").val(),
        };
        // 发送Ajax请求
        $.ajax({
            url: '/Procurement/GetProcurement',  // 这里填上你的后端接口地址
            type: 'get',
            data: dto,
            success: function (response) {
                var res = JSON.parse(response);
                console.log(res);
                if (res != null) {
                    // 渲染表格
                    table.render({
                        elem: '#ID-table',
                        cols: [[
                            { type: 'checkbox', fixed: 'left' },
                            { field: 'procurementCode', title: '订单号', width: 150, fixed: 'left', },
                            { field: 'productsName', title: '产品名称', width: 120 },
                            { field: 'productsCode', title: '产品编号', width: 120 },
                            { field: 'specs', title: '产品规格', width: 120 },
                            { field: 'storageUnits', title: '单位', width: 100 },
                            { field: 'price', title: '单价', width: 100 },
                            { field: 'procurementNum', title: '数量', width: 100 },
                            {
                                field: 'sign',
                                title: '总额',
                                width: 150,
                                templet: function (d) {
                                    return (d.procurementNum * d.price); // 保留两位小数
                                }
                            },
                            { field: 'vendorCode', title: '供应商编号', width: 120 },
                            { field: 'vendorName', title: '供应商名称', width: 170 },
                            {
                                field: 'procureState',
                                title: '状态',
                                width: 100,
                                templet: function (d) {
                                    // 根据状态值显示不同的文字
                                    switch (d.procureState) {
                                        case 0: return '全部入库';
                                        case 1: return '采购中';
                                        case 2: return '部分入库';
                                        case 3: return '订单取消';
                                        default: return '错误状态';
                                    }
                                }
                            },
                            {
                                field: 'isRecorded',
                                title: '是否入账',
                                width: 120,
                                templet: function (d) {
                                    switch (d.isRecorded) {
                                        case 0: return '否';
                                        case 1: return '是';
                                    }
                                }
                            },
                            {
                                field: 'vendorName',
                                title: '操作',
                                width: 250,
                                templet: function (d) {
                                    // 这里的d是每一行的数据对象
                                    return '<a lay-on="test-page" id="detail" data-procureProductId="' + d.procureProductId + '">查看 </a>' +
                                        '<a lay-on="test-del" id="del" data-procureProductId="' + d.procureProductId + '">删除 </a>' +
                                        '<a lay-on="test-fan" class="fan" data-productsID="' + d.productsID + '"  href="/Procurement/UpdProcurement?productsID=' + d.productsID + '&procurementId=' + d.procurementId + '">编辑 </a>' +
                                        '<a lay-on="test-ru" id="ku" data-procureProductId="' + d.procureProductId + '">入库 </a>' +
                                        '<a lay-on="test-tui" id="tui" data-procureProductId="' + d.procureProductId + '">退货 </a>' +
                                        '<a lay-on="test-zhang" id="zhang" data-procureProductId="' + d.procureProductId + '">入账</a>';
                                }
                            },
                        ]],
                        data: res.data.list,  // 数据源
                        page: true,   // 启用分页
                        limit: 10,    // 每页显示多少条数据
                        limits: [10, 20, 30],  // 分页选择项
                        curr: pageNum,  // 当前页
                        total: res.data.lcount,  // 总记录数
                        loading: true, // 启用加载状态
                        toolbar: "#toolbarDemo",
                        defaultToolbar: ['exports']
                    });

                    // 渲染分页控件
                    var totalPages = Math.ceil(res.lcount / 10);  // 计算总页数
                    layui.laypage.render({
                        elem: 'pagination',
                        count: res.lcount,  // 总记录数
                        limit: 10,
                        curr: pageNum,
                        jump: function (obj, first) {
                            if (!first) {
                                Getprocurement(obj.curr);  // 不为第一次调用时，重新渲染表格
                            }
                        }
                    });
                }
            },
            error: function (xhr, status, error) {
                console.log('请求失败: ' + error);
            }
        });
    }

    // 初次加载表格数据
    Getprocurement(1);

    // 查询按钮点击事件
    $('#searchBtn').click(function () {

        Getprocurement(1);  // 重置为第一页，并重新加载数据
    });

    // 获取选中数据按钮
    $('#getSelected').click(function () {
        var checkStatus = table.checkStatus('dataTable');
        var selectedData = checkStatus.data;  // 获取选中的数据
        console.log(selectedData);  // 打印选中的数据
    });


    //获取复选框
    table.on('checkbox(ID-table)', function (obj) {
        console.log(obj);
        // 当前选中的行加入到 selectedRows 数组中
        if (obj.checked) {
            selectedRows.push(obj.data);
        }
        else {
            // 当前取消选中的行从 selectedRows 数组中移除
            selectedRows = selectedRows.filter(row => row.productsID !== obj.data.productsID);
        }
        console.log(selectedRows)
    })


    //查看详情
    $(document).on('click', '#detail', function () {
        var procureProductId = $(this).attr('data-procureProductId');  // 获取按钮上设置的采购ID
        console.log(procureProductId);
        //打开弹框
        var index = layer.open({
            type: 1,
            area: ['750px', '400px'], // 宽高
            content: '<table style="width:650px;height:300px; margin-left:45px">' +
                '<tr>' +
                '<td>订单号:</td>' +
                '<td id="procurementCode">474315</td>' +
                '<td style="width:100px">关联单号：</td>' +
                '<td id="associateNumber" style="width:100px"></td>' +
                '<td style="width:100px">产品名称：</td>' +
                '<td id="productsName">联想电脑</td>' +
                '</tr>' +
                '<tr>' +
                '<td>制单日期：</td>' +
                '<td id="markTime"></td>' +
                '<td>制单人：</td>' +
                '<td id="makePerson"></td>' +
                '<td>电话：</td>' +
                '<td id="phone"></td>' +
                '</tr>' +
                '<tr>' +
                '<td>联系人:</td>' +
                '<td id="pcontact"></td>' +
                '<td>供应商编号：</td>' +
                '<td id="vendorCode"></td>' +
                '<td>供应商名称：</td>' +
                '<td id="vendorName"></td>' +
                '</tr>' +
                '</table>',
            success: function (lay, index) {
                form.render();
            }
        });
        var obj = {
            Token: token,
            ProcureProductId: procureProductId
        }
        $.ajax({
            url: '/Procurement/GetProcurementDetail',
            type: "get",
            data: obj,
            success: (ress) => {
                var res = JSON.parse(ress);
                console.log(res);
                $(res.data).each(function () {
                    console.log(res.data[0])
                    $("#procurementCode").text(this.procurementCode);
                    $("#associateNumber").text(this.associateNumber);
                    $("#productsName").text(this.productsName);
                    $("#markTime").text(this.markTime);
                    $("#makePerson").text(this.makePerson);
                    $("#phone").text(this.phone);
                    $("#pcontact").text(this.pcontact);
                    $("#vendorCode").text(this.vendorCode);
                    $("#vendorName").text(this.vendorName);
                })
            }
        })
    })


    //删除
    $(document).on('click', '#del', function () {
        var procureProductId = $(this).attr('data-procureProductId')
        layer.confirm('确认删除吗？', {
            btn: ['确定', '关闭'] //按钮
        }, function () {
            var model = {
                Token: token,
                ProcureProductId: [
                    procureProductId
                ],
                delName: '张三'
            }
            $.ajax({
                url: '/Procurement/DelProcurement',
                type: 'put',
                data: model,
                success: function (res) {
                    var d = JSON.parse(res);
                    console.log(d);
                    if (d != null) {
                        layer.msg('删除成功', { icon: 1 }, function () {
                            location.reload();
                        });
                    }
                }
            })
        }, function () {
            // 关闭框第二个回调
            layer.msg('操作已取消', {
                time: 2000 // 2秒后自动关闭
            });
        });
    })


    //批量删除
    $(document).on('click', '#bathdel', function () {
        if (selectedRows.length == 0) {
            layer.msg('至少选择一个要删除的数据');  // '5' 是警告图标
            return;
        }
        var procureProductId = selectedRows.map(function (row) {
            return row.procureProductId;
        });
        console.log(procureProductId)
        layer.confirm('确认删除吗？', {
            btn: ['确定', '关闭'] //按钮
        }, function () {
            var model = {
                Token: token,
                procureProductId: procureProductId,
                delName: '张三'
            }
            $.ajax({
                url: '/Procurement/DelProcurement',
                type: 'put',
                data: model,
                success: function (res) {
                    var d = JSON.parse(res);
                    console.log(d);
                    if (d != null) {
                        layer.msg('删除成功', { icon: 1 }, function () {
                            location.reload();
                        });
                    }
                }
            })
        }, function () {
            // 关闭框第二个回调
            layer.msg('操作已取消', {
                time: 2000 // 2秒后自动关闭
            });
        });
    });


    var selectRow = {};


    //退货
    $(document).on('click', "#tui", function () {
        var procureProductId = $(this).attr('data-procureProductId')
        console.log(procureProductId)

        //打开弹框
        var index = layer.open({
            type: 1,
            area: ['1200px', '550px'], // 宽高
            content: '<table style="width:650px;height:300px; margin-left:45px">' +
                '<tr>' +
                '<td>订单号:</td>' +
                '<td id="procurementCode">474315</td>' +
                '<td style="width:100px">关联单号：</td>' +
                '<td id="associateNumber" style="width:100px"></td>' +
                '<td style="width:100px">产品名称：</td>' +
                '<td id="productsName">联想电脑</td>' +
                '</tr>' +
                '<tr>' +
                '<td>制单日期：</td>' +
                '<td id="markTime"></td>' +
                '<td>制单人：</td>' +
                '<td id="makePerson"></td>' +
                '<td>电话：</td>' +
                '<td id="phone"></td>' +
                '</tr>' +
                '<tr>' +
                '<td>联系人:</td>' +
                '<td id="pcontact"></td>' +
                '<td>供应商编号：</td>' +
                '<td id="vendorCode"></td>' +
                '<td>供应商名称：</td>' +
                '<td id="vendorName"></td>' +
                '</tr>' +
                '<table class= "layui-table" id="refund-table" >' +
                '<thead>' +
                '<tr>' +
                '<col width="150">' +
                '<col>' +
                '</tr>' +
                '</thead>' +
                '</table>' +
                '<button type="button" id="addrefund" class="layui-btn layui-bg-blue">提交</button>'
        })
        form.render();


        var obj = {
            Token: token,
            procureProductId: procureProductId,
        }
        console.log(obj);
        //显示操作列的退货的显示
        $.ajax({
            url: '/Procurement/GetRefundDetail',
            type: 'get',
            data: obj,
            success: function (res) {
                var d = JSON.parse(res);
                console.log(d);
                if (d != null) {
                    // 渲染表格
                    table.render({
                        elem: '#refund-table',
                        cols: [[
                            { field: 'productsCode', title: '产品编号', width: 150 },
                            { field: 'productsName', title: '产品名称', width: 150 },
                            { field: 'specs', title: '产品规格', width: 150 },
                            { field: 'storageUnits', title: '单位', width: 150 },
                            { field: 'price', title: '单价', width: 150 },
                            { field: 'procurementNum', title: '数量', width: 150 },
                            { field: 'batch', title: '批次', width: 120, edit: 'textarea' },
                            { field: 'refundNum', title: '退货数', width: 120, edit: 'textarea' },
                            {
                                field: 'sign',
                                title: '总额',
                                width: 150,
                                templet: function (d) {
                                    return (d.procurementNum * d.price); // 保留两位小数
                                }
                            },

                        ]],
                        data: d.data,  // 数据源
                        done: function (res, curr, count) {
                            table.on('edit(refund-table)', function (obj) {
                                var value = obj.value // 得到修改后的值
                                var data = obj.data // 得到所在行所有键值
                                var field = obj.field; // 得到字段
                                selectRow = data;
                                console.log(selectRow)

                            });
                        }
                    });


                    //反填采购
                    $(d.data).each(function () {
                        console.log(this);

                        var date1 = new Date(this.markTime);

                        // 获取年、月、日
                        var year1 = date1.getFullYear();
                        var month1 = (date1.getMonth() + 1).toString().padStart(2, '0');  // 月份从0开始，因此加1
                        var day1 = date1.getDate().toString().padStart(2, '0');  // 补充两位数字

                        // 拼接成 "yyyy-MM-dd" 格式
                        var markTimes = `${year1}-${month1}-${day1}`;

                        $("#procurementCode").text(this.procurementCode); //采购单号
                        $("#associateNumber").text(this.associateNumber);  //关联订单号
                        $("#markTime").text(markTimes);  //制单时间
                        $("#makePerson").text(this.makePerson); //制单人
                        $("#phone").text(this.phone); //电话
                        $("#pcontact").text(this.pcontact);  //联系人
                        $("#vendorCode").text(this.vendorId); //供应商名
                        layui.form.render('select');
                        $("#vendorName").text(this.vendorName); //客户名称
                        layui.form.render('select');

                    })


                }
            }
        })


        //点击提交添加退货数量
        $("#addrefund").on('click', function () {
            var code = Math.floor(Math.random() * 1000000) + 100000;   //随机数
            var model = {
                IsRefund: 1,
                RefundCode: code,
                procurementId: selectRow.procurementId,
                ProductsID: selectRow.productsID,
                RefundNum: selectRow.refundNum,
                batch: selectRow.batch,
                Token: token
            }

            $.ajax({
                url: '/Procurement/AddProcureRefund',
                type: 'post',
                data: model,
                success: function (res) {
                    var d = JSON.parse(res);
                    if (d != null) {
                        layer.msg('添加成功', { icon: 1 }, function () {
                            location.reload();
                        });
                    }
                    else {
                        layer.msg('添加失败');
                    }
                }
            })
        })

    })


    //点击编辑
    $(document).on('click', "#upd", function () {
        console.log(selectedRows)
        if (selectedRows.length != 1) {
            layer.msg('请选择一个要修改的数据');  // '5' 是警告图标
            return;
        }
        var procurementId = selectedRows[0].procurementId
        var productsID = selectedRows[0].productsID
        location.href = '/Procurement/UpdProcurement?productsID=' + productsID + '&procurementId=' + procurementId;
    })


    //入库
    $(document).on('click', "#ku", function () {
        
        var procureProductId = $(this).attr('data-procureProductId');  // 获取按钮上设置的采购ID
        console.log(procureProductId);

        //打开弹框
        var index = layer.open({
            type: 1,
            area: ['1000px', '600px'], // 宽高
            content: '<table style="width:650px;height:300px; margin-left:45px">' +
                '<tr>' +
                '<td>订单号:</td>' +
                '<td id="procurementCode">474315</td>' +
                '<td style="width:100px">关联单号：</td>' +
                '<td id="associateNumber" style="width:100px"></td>' +
                '<td style="width:100px">产品名称：</td>' +
                '<td id="productsName">联想电脑</td>' +
                '</tr>' +
                '<tr>' +
                '<td>制单日期：</td>' +
                '<td id="markTime"></td>' +
                '<td>制单人：</td>' +
                '<td id="makePerson"></td>' +
                '<td>电话：</td>' +
                '<td id="phone"></td>' +
                '</tr>' +
                '<tr>' +
                '<td>联系人:</td>' +
                '<td id="pcontact"></td>' +
                '<td>供应商编号：</td>' +
                '<td id="vendorCode"></td>' +
                '<td>供应商名称：</td>' +
                '<td id="vendorName"></td>' +
                '</tr>' +
                '</table>' +
                '<table class= "layui-table" id="storages-table" >' +
                '</table>' +
                '<button type="button" id="addstorages" class="layui-btn layui-bg-blue">提交</button>',
            
        });

        
        //反填
        var obj = {
            Token: token,
            procureProductId: procureProductId,
        }
        $.ajax({
            url: '/Procurement/GetRefundDetail',
            type: 'get',
            data: obj,
            success: function (res) {
                var d = JSON.parse(res);
                console.log(d);
                if (d != null) {
                    storageNums = d.data[0].procurementNum
                    console.log(storageNums)
                    // 渲染表格
                    table.render({
                        elem: '#storages-table',
                        css: [
                            // 设置单元格样式
                            // 取消默认的溢出隐藏，并设置适当高度
                            '.layui-table-cell{height: 50px; line-height: 40px;}',
                            '.layui-table-cell .layui-colorpicker{width: 38px; height: 38px;}',
                            '.layui-table-cell select{height: 36px; padding: 0 5px;}',
                        ].join(''),
                        cols: [[
                            { field: 'productsCode', title: '产品编号', width: 150 },
                            { field: 'productsName', title: '产品名称', width: 150 },
                            { field: 'specs', title: '产品规格', width: 150 },
                            { field: 'storageUnits', title: '单位', width: 150 },
                            { field: 'procurementNum', title: '数量', width: 150 },
                            { field: 'batch', title: '批次', width: 120, edit: 'textarea' },
                            {field: 'storageNum',title: '入库数',width: 120,edit: 'textarea' },
                            { field: 'storehouseId', title: '库位', minWidth: 150, templet: '#TPL-select' },
                            { field: 'price', title: '单价', width: 150 },
                            {
                                field: 'sign',
                                title: '总额',
                                width: 150,
                                templet: function (d) {
                                    return (d.procurementNum * d.price); // 保留两位小数
                                }
                            },

                        ]],
                        data: d.data,  // 数据源
                        done: function (res, curr, count) {
                            table.on('edit(storages-table)', function (obj) {
                                var value = obj.value // 得到修改后的值
                                var data = obj.data // 得到所在行所有键值
                                var field = obj.field; // 得到字段
                                storageslis = data;
                                console.log(storageslis)
                            });

                            $.ajax({
                                url: '/Procurement/GetStorageList',
                                type: "get",
                                data: {
                                    Token: token,
                                    StoreCode: null,
                                    StoreName: null,
                                    pageIndex: 1,
                                    PageSize: 100,
                                    wid: 0,
                                    cacheBuster: new Date().getTime()  // 添加时间戳，防止缓存
                                },
                                success: function (res) {
                                    var d = JSON.parse(res);
                                    console.log(d);
                                    var suppliers = d.data.list;

                                    var selectContent = '<option value="">请选择库位</option>';

                                    // 循环遍历供应商数据并填充下拉框
                                    suppliers.forEach(function (item) {
                                        console.log(item);
                                        selectContent += '<option value="' + item.storehouseId + '">' + item.storehouseName + '</option>';
                                    });

                                    console.log(selectContent);
                                    $('#city').html(selectContent);  // 填充选项
                                    form.render();  // 渲染 select
                                }
                            })

                            form.on('select(select-demo)', function (obj) {
                                console.log(obj);
                                var value = obj.value; // 获取选中项 value
                                // 获取当前行数据(如 id 等字段，以作为数据修改的索引)
                                console.log(value);
                                storageselect = value;


                            });
                        }
                    });


                    //反填采购
                    $.ajax({
                        url: '/Procurement/GetProcurementDetail',
                        type: "get",
                        data: obj,
                        success: (ress) => {
                            var res = JSON.parse(ress);
                            console.log(res);
                            $(res.data).each(function () {
                                console.log(res.data[0])

                                let markTime = new Date(this.markTime);

                                // 格式化日期为 yyyy-mm-dd
                                let formattedDate = markTime.getFullYear() + '-' +
                                    (markTime.getMonth() + 1).toString().padStart(2, '0') + '-' +
                                    markTime.getDate().toString().padStart(2, '0');

                                $("#procurementCode").text(this.procurementCode);
                                $("#associateNumber").text(this.associateNumber);
                                $("#productsName").text(this.productsName);
                                $("#markTime").text(formattedDate);
                                $("#makePerson").text(this.makePerson);
                                $("#phone").text(this.phone);
                                $("#pcontact").text(this.pcontact);
                                $("#vendorCode").text(this.vendorCode);
                                $("#vendorName").text(this.vendorName);
                            })
                        }
                    })


                }
            }
        })


        //点击提交
        $(document).on('click', '#addstorages', function () {
            // 点击提交
            console.log(storageslis.storageNum)
            console.log(storageNums)
            if (storageslis.storageNum < storageNums) {
                var models = {
                    ProcurementId: storageslis.procurementId,
                    ProductsID: storageslis.productsID,
                    Batch: storageslis.batch,
                    StorageNum: storageslis.storageNum,
                    StorehouseId: storageselect,
                    Token: token,
                    ProcureState: 2
                }
            }
            else if(storageslis.storageNum == storageNums) {
                var models = {
                    ProcurementId: storageslis.procurementId,
                    ProductsID: storageslis.productsID,
                    Batch: storageslis.batch,
                    StorageNum: storageslis.storageNum,
                    StorehouseId: storageselect,
                    Token: token,
                    ProcureState: 0
                }
            }
            else if (storageslis.storageNum > storageNums) {
                layer.msg('入库数大于产品数量', { icon: 0 }, function () {
                });
            }
            console.log(models);
            $.ajax({
                url: '/Procurement/AddStorages',
                type: 'post',
                data: models,
                success: function (ress) {
                    var res = JSON.parse(ress);
                    console.log(res);
                    if (res != null) {
                        layer.msg('入库成功', { icon: 1 }, function () {
                            location.reload();
                        });
                    }
                    else {
                        layer.msg('入库失败', { icon: 1 }, function () {
                            location.reload();
                        });
                    }
                }
            })
        })
        

        
    })


    //入账
    $(document).on('click', "#zhang", function () {
        var procureProductId = $(this).attr('data-procureProductId');  // 获取按钮上设置的采购ID
        var data = {
            Token: token,
            procureProductId: procureProductId,
            isRecorded:1
        }
        $.ajax({
            url: '/Procurement/UpdRecorded',
            type: 'post',
            data: data,
            success: function (d) {
                layer.msg('入账成功', {
                    icon: 1,
                    offset: 'rb'
                }, function () {
                    location.reload();
                });
            }
        })


    })
    

});